package com.springcloud.market.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.springcloud.market.order.entity.Order;
import com.springcloud.market.order.feign.StockFeignService;
import com.springcloud.market.order.mapper.OrderMapper;
import com.springcloud.market.order.service.IOrderService;
import com.springcloud.market.order.service.OrderTimeoutSender;
import io.seata.spring.annotation.GlobalTransactional;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Resource
    private StockFeignService stockFeignService;
    //2025-10-28
    @Autowired
    private OrderTimeoutSender orderTimeoutSender;

    @Override
    public String deduct(Integer productId, Integer num) {
        String stockResp =stockFeignService.reduceStock(productId,num);
        if (!stockResp.contains("成功")) return stockResp;

        //2,写库存
        Order o = new Order();
        o.setProductId(productId);
        baseMapper.insert(o);
        return "下单成功，订单号=" + o.getId();
    }

    @Override
    @GlobalTransactional
    public String createOrder(Integer productId, Integer num) {
        // 1. 扣库存
        String stockResp = stockFeignService.reduceStock(productId, num);
        if (!stockResp.contains("成功")) {
            return "下单失败：" + stockResp;
        }

        // 2. 写订单
        Order o = new Order();
        o.setProductId(productId);
        baseMapper.insert(o); // MP 自带

        return "下单成功，订单号=" + o.getId();
    }


    //2025-10-28
//    @Override
    public Order createOrder(){
        Integer orderId=202;
        try{
            orderTimeoutSender.sendOrderTimeoutMessage(orderId.toString());
        }catch (Exception e){
            System.err.println("发送超时消息失败："+e.getMessage());
        }
        return new Order(orderId,203);
    }
}
